﻿<template>
    <div style="height: 100%">
        <!-- 扫码 -->
        <navbar :title="$t('scan')" :backCallback="goBack"></navbar>
        <div class="content">
            <div style="padding: 20px;">
                <!-- 无效二维码 -->
                <v-alert v-if="data.busType && data.busType === 'INVALID'" type="warning" show-icon>
                    <van-icon name="info-o" slot="icon"/>
                    <template slot>
                        <p> {{ $t('invalid_qr_code') }} </p>
                    </template>
                </v-alert>
                <!-- 纯文本显示 -->
                <v-alert v-else-if="content" type="info" show-icon>
                    <van-icon name="info-o" slot="icon"/>
                    <template slot>
                        <p> {{ content }} </p>
                    </template>
                </v-alert>
                <!-- 错误提示 -->
                <div v-if="verifyData && verifyData.code && verifyData.code !== 200">
                    <v-alert type="error" show-icon>
                        <van-icon name="info-o" slot="icon"/>
                        <template slot>
                            <p> {{ verifyData.msg }} </p>
                        </template>
                    </v-alert>
                    <van-row v-if="verifyData.data.title">
                        <!-- 标题 -->
                        <van-col span="6" class="van-col-text">{{ $t('title') }}：</van-col>
                        <van-col span="18" class="van-col-text">{{ verifyData.data.title }}</van-col>
                    </van-row>
                    <van-row v-if="verifyData.data.type">
                        <!-- 类型 -->
                        <van-col span="6" class="van-col-text">{{ $t('class_date') }}：</van-col>
                        <van-col span="18" class="van-col-text">{{ verifyData.data.type }}</van-col>
                    </van-row>
                </div>
            </div>
        </div>
        <common-loading :isLoading="isLoading"></common-loading>
    </div>
</template>

<script>
import CommonLoading from '@/components/common/loading';
import {Col, Row} from 'vant';
import MobileDetect from 'mobile-detect';
let Base64 = require('js-base64').Base64;
export default {
    name: 'qrcode_index',
    components: {CommonLoading, vanCol: Col, vanRow: Row},
    data() {
        return {
            isLoading: true,
            code: this.$route.query.code,
            content: '',
            errMsg: '',
            data: {
                busType: '', // 业务类型
                isAuth: '', // 是否需要授权
                route: '', // 路由
                content: '' // 内容
            },
            verifyData: { // 验证数据
                code: null, // code
                msg: '', // 消息
                data: { // 业务数据
                    type: '', // 类型
                    title: '' // 标题
                }
            },
            userAgent: 'app', // 代理app、weixin（微信）、wxwork（企业微信）【默认app】
            queryParams: {} // 目标路由参数，用于获取微信授权后的重定向回来的路由参数
        };
    },
    methods: {
        /**
         * 返回
         */
        goBack() {
            const token = window.localStorage.getItem('token');
            if (token) {
                this.$router.push({path: '/home'});
                return;
            }
            switch (this.userAgent) {
            case 'wechat':
                this.$router.push({path: '/wxLogin'});
                break;
            default:
                this.$router.push({path: '/'});
                break;
            }
        },
        /**
         * 初始化
         */
        init() {
            new Promise((resolve) => {
                this.isLoading = false;
                this.content = '';
                this.errMsg = '';
                this.data = {
                    busType: '', // 业务类型
                    isAuth: '', // 是否需要授权
                    route: '', // 路由
                    content: '' // 内容
                };
                this.verifyData = { // 验证数据
                    code: null, // code
                    msg: '', // 消息
                    data: { // 业务数据
                        type: '', // 类型
                        title: '' // 标题
                    }
                };
                let ua = navigator.userAgent;
                let md = new MobileDetect(ua);
                this.userAgent = md.os() ? 'app' : ''; // app
                this.userAgent = ua.match(/MicroMessenger/i) ? 'weixin' : this.userAgent; // 微信
                // this.userAgent = ua.match(/wxwork/i) ? 'wxwork' : this.userAgent; // 企业微信
                if (this.userAgent) {
                    resolve();
                }
            }).then(() => {
                // 获取二维码信息
                this.getQRCodeInfo().then(() => {
                    if (this.data.busType !== 'INVALID') {
                        this.checkLogin();
                    }
                });
            });
        },
        /**
         * 获取二维码信息
         */
        async getQRCodeInfo() {
            this.isLoading = true;
            let params = {
                code: this.code
            };
            await this.$axios.get(`/app/api/QRCode/info`, {params}).then((res) => {
                this.isLoading = false;
                this.data = res.data;
            });
        },
        // 验证登录信息
        checkLogin() {
            // 如果不需要授权，直接跳转
            if (this.data.isAuth !== 1) {
                this.onJumpTo();
                return;
            }
            // 需要授权，验证登录
            const token = window.localStorage.getItem('token');
            // 如果已经登录，验证业务权限
            if (token) {
                this.verifyPermissions();
                return;
            }
            switch (this.userAgent) {
            case 'weixin':
                // 微信登录后重定向到当前页面 this.$route.fullPath Base64编码
                this.$router.push({path: '/wxLogin?state=' + Base64.encode(this.$route.fullPath)});
                break;
            // case 'wxwork':
            //     this.$router.push({path: '/loginIndex'});
            //     break;
            default: // app登录后重新扫码，基本上不存在这种情况（app登录后扫码）
                this.$router.push({path: '/loginIndex'});
                break;
            }
        },
        /**
         * 验证业务权限
         */
        verifyPermissions() {
            this.isLoading = true;
            let params = {
                code: this.code
            };
            this.$axios.get(`/app/api/QRCode/verify/permissions`, {params}).then((res) => {
                this.isLoading = false;
                this.verifyData = res.data;
                if (this.verifyData.code === 200) {
                    this.onJumpTo();
                }
            });
        },
        /**
         * 跳转
         */
        onJumpTo() {
            // 清除标记
            window.sessionStorage.removeItem('qrcode_mark');
            if (!this.data) {
                return;
            }
            if (this.data.route) {
                this.$router.push({path: this.data.route});
                return;
            }
            if (this.data.content && this.data.content.includes('http')) {
                window.location.href = this.data.content;
                return;
            }
            this.content = this.data.content;
        }
    },
    mounted() {
        // 判断是否是二维码扫描进入
        if (window.sessionStorage.getItem('qrcode_mark')) {
            this.init();
        } else {
            this.goBack();
        }
    }
};
</script>

<style scoped lang="less">
.van-col-text {
    padding: 10px 0;
}
.van-col-text:nth-child(odd) {
    text-align: right;
}
.van-col-text:nth-child(even) {
    text-align: left;
}
</style>
